package filter;
import model.User;
import utils.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    // 路径匹配器，支持通配符
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        // 获取本次请求的路径
        String requestURI = request.getRequestURI();
        // 定义不需要请求的路径
        String[] urls=new String[]{
                "/css/**.css",
                "/img/**",
                "/js/**.js",
                "/blog_login.jsp",
                "/login",
                "/logout",
                "/loginMD",
                "/reg.jsp",
                "/reg",
                "/index.html"
        };
        // 放行不需要处理的请求
        for (String url:urls){
            boolean match = PathMatcher.match(url, requestURI);
            if (match){
                filterChain.doFilter(request,response);
                return;
            }
        }
        // 需要处理，检查登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user")!=null){
            // 已登录，放行
            User user= (User) request.getSession().getAttribute("user");
            Long userId= (long) user.getUserId();
            BaseContext.setCurrentUserId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //如果未登录重定向到登录页

        response.sendRedirect("blog_login.jsp");
        return;
    }

    @Override
    public void destroy() {

    }
}
